package com.iehyou.utils;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import org.apache.log4j.Logger;

/**
 * 读取config文件夹下所有的properties文件到内存.
 * @author Administrator
 *
 */
public class GlobalConfigUtils {
	private final static Logger log = Logger.getLogger(GlobalConfigUtils.class); 
	/**
	 * 保存config下的配置文件key[文件名]-value[Properties];
	 */
	public static Map<String, Properties> p=new HashMap<String, Properties>();
	
	/**
	 * 获取项目编译根路径
	 */
	public static String appConfigPath;
	/**
	 * 是否是window环境
	 */
	public static boolean isWindows;
	
	static{
		try {
			InputStream is2 = GlobalConfigUtils.class.getResourceAsStream("/db.properties");
			Properties _p2=new Properties();
			_p2.load(is2);
			p.put("db.properties", _p2);
			
			log.info("存储方式:"+getValue("jdbc.database"));
		} catch (Exception e) {
			log.error(e.toString(),e);
			e.printStackTrace();
		}
	}
	
	
	
	/**
	 * 根据key获取config/下的配置文件的值
	 * @param key
	 * @return
	 */
	public static String getValue(String key){
		String _return=null;
		for(Entry<String, Properties> entry: p.entrySet()) {
		     Properties _p=entry.getValue();
		     String _value=(String) _p.get(key);
		     if(_value!=null){
		    	 try {
					_return = new String(_value.trim().getBytes("ISO-8859-1"),"UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
		    	 break;
		     }
		}
		return _return;
	}
	
	/**
	 * 根据key获取config/下的配置文件的值
	 * @param key
	 * @return
	 */
	public static String getValue(String key,String defaultVal){
		String _return=getValue(key);
		if(_return == null||"".equals(_return.trim())){
			return defaultVal;
		}
		return _return;
	}
	
	
	/**
	 * 获取key的值
	 * @param key
	 * @param defaultVal
	 * @param scope
	 * @return
	 */
	public static String getValue(String key,String defaultVal,String[] scope){
		String _return=getValue(key);
		
		if(_return == null||"".equals(_return.trim())){
			return defaultVal;
		}else{
			boolean isScope=false;
			for (int i = 0; i < scope.length; i++) {
				if(_return.equals(scope[i])){
					isScope = true;
					break;
				}
			}
			if(!isScope){
				return defaultVal;
			}
		}
		return _return;
	}
	
	
	
	/**
	 * 根据key获取config/下的配置文件
	 * @param key
	 * @return
	 */
	public static Properties getProperties(String key){
		return p.get(key);
	}
	
	public static void main(String[] args) {
		String val = GlobalConfigUtils.getValue("textinfo.position","2",new String[]{"1","2"});
		System.out.println(val);
	}
}
